# coding:utf-8
from typing import Optional, Union

from fastapi import APIRouter, Query, Path, Body, Security
from pydantic import BaseModel, Field
from tortoise.expressions import Q

from app.admin.schemas.system import SystemMenuBase, SystemMenuUpdate
from app.admin.service.system.menu import SystemMenuService
from app.core.response import SuccessExtra, Success, Fail
from app.dependencies.verify import verify_token

router = APIRouter()


# 定义 Pydantic 模型来表示 POST 请求的 body 参数
class SearchIn(BaseModel):
    name: str = Field(None, description="用户名称，用于搜索")
    status: Union[str, int] = Field(None, description="用户名称，用于搜索")


@router.post("/menu/list", summary="菜单列表", dependencies=[Security(verify_token, scopes=["system:menu:list"])])
async def page_list(search: SearchIn):
    # 查询条件
    query = Q()
    if search.name:
        query &= Q(menu_name__contains=search.name)
    if search.status and int(search.status) in [0, 1]:
        query &= Q(status=search.status)
    model_service = SystemMenuService()
    lists = await model_service.tree_list(query)
    return Success(data=lists)


@router.get("/menu/{item_id}", summary="查看菜单")
async def get_detail(item_id: int = Path(..., description="菜单ID"), ):
    model_service = SystemMenuService()
    user_obj = await model_service.get_id(item_id)
    if not user_obj:
        return Fail(msg="菜单不存在")
    user_dict = await user_obj.to_dict(exclude_fields=["password"])
    return Success(data=user_dict)


@router.post("/menu/create", summary="创建菜单")
async def create(data_in: SystemMenuBase):
    model_service = SystemMenuService()
    # 查询条件
    # query = Q()
    # query &= Q(pid__eq=data_in.pid)
    # role = await model_service.find(query)
    # if not role:
    #     return Fail(msg="上级菜单目录不可用")
    new_role = await model_service.create(obj_in=data_in)
    # await model_service.update_roles(new_user, user_in.roles)
    if not new_role:
        return Fail(msg="操作失败")
    return Success(msg="操作成功")


@router.post("/menu/update", summary="更新菜单")
async def update(data_in: SystemMenuUpdate):
    model_service = SystemMenuService()
    user = await model_service.update(obj_in=data_in)
    # await model_service.update_roles(user, user_in.roles)
    return Success(msg="操作成功")


@router.delete("/menu/delete/{item_id}", summary="删除菜单")
async def delete(item_id: int = Path(..., description="菜单ID")):
    model_service = SystemMenuService()
    child_menu_count = await model_service.get_child_count(item_id)
    if child_menu_count > 0:
        return Fail(msg="请先删除子菜单")
    await model_service.remove(item_id)
    return Success(msg="操作成功")
